package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.ShopNew;
import com.ramos.kuaixiao.entity.ShopTypeBean;

import java.util.ArrayList;
import java.util.List;

public class ShopsDB {
    private static String TAG = "ShopsDB";
    private static String TABLE_NAME = "Shops";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "idx" + " CHAR(30) PRIMARY KEY NOT NULL,"
                + "productInfoId" + " CHAR(30)," + "productInfoName" + " CHAR(30)," + "productBarCode" + " CHAR(30)," + "productFirstTypeId"
                + " CHAR(30)," + "productTypeName" + " CHAR(30),"  + "outerUnitCount" + " INTEGER," + "brandName" + " CHAR(30)," + "brandId" + " CHAR(30)," +
                 "nonTaxSalePrice" + " CHAR(30)," + "taxrate" + " FLOAT," + "status" + " CHAR(30),"+  "modifyTime" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllShops(List<ShopTypeBean.ShopType.ProductInfo> customer) {
        //deleteAll();
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM Shops");
        String sql = "insert into Shops(productInfoId,productInfoName,productBarCode,productFirstTypeId,productTypeName," +
                ",outerUnitCount,brandName,brandId,nonTaxSalePrice,taxrate,status,modifyTime) values(?,?,?,?,?,?,?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getProductInfoId() + "");
            stmt.bindString(2, customer.get(i).getProductInfoName() + "");
            stmt.bindString(3, customer.get(i).getProductBarCode() + "");
            stmt.bindString(4, customer.get(i).getProductFirstTypeId() + "");
            stmt.bindString(5, customer.get(i).getProductTypeName() + "");
            stmt.bindString(6, customer.get(i).getOuterUnitCount() + "");
            stmt.bindString(7, customer.get(i).getBrandName() + "");
            stmt.bindString(8, customer.get(i).getBrandId() + "");
            stmt.bindString(9, customer.get(i).getNonTaxSalePrice() + "");
            stmt.bindString(10, customer.get(i).getTaxrate() + "");
            stmt.bindString(11, customer.get(i).getStatus() + "");
            stmt.bindString(12, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllShops(List<ShopTypeBean.ShopType.ProductInfo> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllShops:" + customer.size());
        for (int i = 0; i < customer.size(); i++) {
            ShopTypeBean.ShopType.ProductInfo firstWarehouse = customer.get(i);
            ContentValues cv = new ContentValues();
            cv.put("idx", firstWarehouse.getProductInfoId() + "");
            cv.put("productInfoId", firstWarehouse.getProductInfoId() + "");
            cv.put("productInfoName", firstWarehouse.getProductInfoName() + "");
            cv.put("productBarCode", firstWarehouse.getProductBarCode() + "");
            cv.put("productFirstTypeId", firstWarehouse.getProductFirstTypeId() + "");
            cv.put("productTypeName", firstWarehouse.getProductTypeName() + "");
            cv.put("outerUnitCount", firstWarehouse.getOuterUnitCount() + "");
            cv.put("brandName", firstWarehouse.getBrandName() + "");
            cv.put("brandId",  firstWarehouse.getBrandId() + "");
            cv.put("nonTaxSalePrice", firstWarehouse.getNonTaxSalePrice() + "");
            cv.put("taxrate", firstWarehouse.getTaxrate() + "");
            cv.put("status", firstWarehouse.getStatus() + "");
            cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
            db.insertWithOnConflict("Shops",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ;

            // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
            //db.insertWithOnConflict("StoreNum",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public boolean hasProduct(String productInfoId) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Shops where productInfoId =?", new String[]{productInfoId});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "hasStoreNum true");
            return true;
        } else {
            Log.d(TAG, "hasStoreNum false");
            cursor.close();
            return false;
        }
    }

    public List<ShopTypeBean.ShopType.ProductInfo> findAllShops() {
        List<ShopTypeBean.ShopType.ProductInfo> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Shops", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
                ShopTypeBean.ShopType.ProductInfo customer = new ShopTypeBean.ShopType.ProductInfo();
                customer.setProductInfoId(cursor.getString(1));
                customer.setProductInfoName(cursor.getString(2));
                customer.setProductBarCode(cursor.getString(3));
                customer.setProductFirstTypeId(cursor.getString(4));
                customer.setProductTypeName(cursor.getString(5));
                customer.setOuterUnitCount(cursor.getInt(6));
                customer.setBrandName(cursor.getString(7));
                customer.setBrandId(cursor.getString(8));
                customer.setNonTaxSalePrice(cursor.getString(9));
                customer.setTaxrate(cursor.getFloat(10));
                customer.setStatus(cursor.getString(11));
                list.add(customer);
        }
        cursor.close();
        return list;
    }

    public List<ShopTypeBean.ShopType.ProductInfo> findShopsById(String productInfoId) {
        List<ShopTypeBean.ShopType.ProductInfo> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Shops where productInfoId =?", new String[]{productInfoId});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();

                ShopTypeBean.ShopType.ProductInfo customer = new ShopTypeBean.ShopType.ProductInfo();
                customer.setProductInfoId(cursor.getString(1));
                customer.setProductInfoName(cursor.getString(2));
                customer.setProductBarCode(cursor.getString(3));
                customer.setProductFirstTypeId(cursor.getString(4));
                customer.setProductTypeName(cursor.getString(5));
                customer.setOuterUnitCount(cursor.getInt(6));
                customer.setBrandName(cursor.getString(7));
                customer.setBrandId(cursor.getString(8));
                customer.setNonTaxSalePrice(cursor.getString(9));
                customer.setTaxrate(cursor.getFloat(10));
                customer.setStatus(cursor.getString(11));
                list.add(customer);

        }
        cursor.close();
        return list;
    }


    public List<ShopTypeBean.ShopType.ProductInfo> findAllUseShops() {
        List<ShopTypeBean.ShopType.ProductInfo> tmpList = new ArrayList<>();
        List<ShopTypeBean.ShopType.ProductInfo> list= findAllShops();
        Log.d(TAG, "findAllShops:" + list.size());
        List<ShopNew> shopNews = new BrandDB().findAllNoEmptyBrand();
        Log.d(TAG, "findAllshopNews:" + shopNews.size());
        if(shopNews.size() > 0){
            for(ShopTypeBean.ShopType.ProductInfo productInfo : list){
                for(ShopNew shopNew : shopNews){
                    if(productInfo.getBrandId().equals(shopNew.getBrandId())){
                        tmpList.add(productInfo);
                    }
                }
            }
        }
        Log.d(TAG, "findAllshopNews:" + tmpList.size());
        return tmpList;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from Shops ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public String getDefaultPrice(String productInfoId) {
        String defaultPrice ="";
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Shops where productInfoId=?", new String[]{productInfoId});
        Log.d(TAG, "cursor:" + cursor.getCount());
        if (cursor.moveToFirst()) {
            defaultPrice = String.valueOf(Double.valueOf(cursor.getString(9)) * ((100 + cursor.getFloat(10)) /100));
        }
        cursor.close();
        //db.close();
        return defaultPrice;
    }

    public String getTaxRate(String productInfoId) {
        String taxRate ="";
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from Shops where productInfoId=?", new String[]{productInfoId});
        Log.d(TAG, "cursor:" + cursor.getCount());
        if (cursor.moveToFirst()) {
            taxRate = String.valueOf(cursor.getFloat(10));
        }
        cursor.close();
        //db.close();
        return taxRate;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM Shops");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from Shops", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasShops true");
            return true;
        } else {
            Log.d(TAG, "hasShops false");
            cursor.close();
            return false;
        }
    }

    public long dataNum() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from Shops", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasShops true");
            return count;
        } else {
            Log.d(TAG, "hasShops false");
            cursor.close();
            return count;
        }
    }

}
